import ProgressBar from "@/components/progressBar"
import { MoneyFormat } from "@/utils/format"
import { View, Text, Button, Input } from "@tarojs/components"
import React, { useEffect, useImperativeHandle, useMemo, useState } from "react"
import http from '@/request'
import { AtModal, AtModalAction, AtModalContent, AtModalHeader } from "taro-ui"
import { HideLoading, ShowLoading, ShowToast } from "@/utils"
import viewMode from "@/store/viewMode"
import moment from "moment"
import "./index.scss"

interface MonthInfo {
    income: number,
    expense: number,
    total: number,
    month?: string,
    accountId?: number
}

let inputTargetVal = 0
let init = false

const MonthInfo = React.forwardRef<{ queryTarget: (data: MonthInfo) => void }, any>((_, ref) => {

    const [editVisible, setEditVisible] = useState(false)
    const [expenseTarget, setExpenseTarget] = useState(0)
    const [monthInfo, setMonthInfo] = useState<MonthInfo>({
        income: 0,
        expense: 0,
        total: 0
    })

    const queryTarget = (data: MonthInfo) => {
        http.post('/expense-target/query', {
            accountId: data.accountId,
            month: data.month
        }).then(res => {
            setMonthInfo(data)
            setExpenseTarget(res.data?.target || 0)
        }).catch(err => {
            ShowToast(err.msg || '获取本月目标失败')
        })
    }

    const dateProgress = useMemo(() => {
        if (monthInfo.month) {
            const month = moment(monthInfo.month).month()
            const curMonth = moment().month()
            if (moment(monthInfo.month).endOf('month') > moment().endOf('month')) {
                return '0%'
            }
            if (month < curMonth) {
                return '100%'
            }
            return 100 * moment().date() / moment().endOf('month').date() + '%'
        } else {
            return '0%'
        }
    }, [monthInfo])

    const updateTarget = () => {
        ShowLoading('保存中...')
        http.post('/expense-target/update', {
            accountId: monthInfo.accountId,
            month: monthInfo.month,
            target: inputTargetVal
        }).then(() => {
            setEditVisible(false)
            setExpenseTarget(inputTargetVal)
            HideLoading()
        }).catch(err => {
            ShowToast(err.msg || '保存本月目标失败')
        })
    }

    useImperativeHandle(ref, () => {
        return {
            queryTarget
        }
    }, [])

    useEffect(() => {
        if (init) {
            viewMode.setBehind(editVisible)
        }
        init = true
    }, [editVisible])

    return <View>
        <View className="month-data need-filter text-main-color card-background">
            <View className="flex-row">
                <View className="title font-size24">{moment(monthInfo.month).format('YYYY-MM')}月概要</View>
            </View>
            <View className="flex-row">
                <View className="flex1"></View>
                <Text className="label font-size20">{expenseTarget ? '预算完成率' : '本月未设置预算'}</Text>
            </View>
            <View className="date-progress flex-row">
                <View className="mark-container flex-row">
                    {new Array(Math.floor(moment(monthInfo.month).daysInMonth() / 7)).fill('').map((_, index) => {
                        return <View className="mark-content border-main-color flex7" key={index}></View>
                    })}
                    <View style={{ flex: moment(monthInfo.month).daysInMonth() % 7 }}></View>
                </View>
                <View className="date-progress-val flex-row" style={{ width: dateProgress }}>
                    <View className="flex1"></View>
                    <View className="guide-icon font-size24 iconfont icon-flag"></View>
                </View>
            </View>
            <ProgressBar value={expenseTarget ? monthInfo.expense * 100 / expenseTarget : 0}></ProgressBar>
            <View className="info-list font-size20 flex-row">
                <View className="info-item">
                    <View className="info-item-val">{MoneyFormat(monthInfo.income)}</View>
                    <View className="info-item-name">收入</View>
                </View>
                <View className="flex1"></View>
                <View className="info-item">
                    <View className="info-item-val">{MoneyFormat(monthInfo.expense)}</View>
                    <View className="info-item-name">实际支出</View>
                </View>
                <View className="flex1"></View>
                <View className="info-item" onClick={() => setEditVisible(true)}>
                    <View className="info-item-val">
                        <Text>{MoneyFormat(expenseTarget)}</Text>
                        <Text className="iconfont icon-base-edit2 edit-btn"></Text>
                    </View>
                    <View className="info-item-name">{expenseTarget ? '支出预算' : '未设预算'}</View>
                </View>
                <View className="flex1"></View>
                <View className="info-item">
                    <View className="info-item-val">{monthInfo.total}笔</View>
                    <View className="info-item-name">本月记账</View>
                </View>
            </View>
        </View>
        <AtModal isOpened={editVisible} className="edit-modal" onClose={() => setEditVisible(false)}>
            <AtModalHeader>编辑本月预算</AtModalHeader>
            <AtModalContent>
                {
                    editVisible ? <Input className="target-val-input" value={`${expenseTarget}`} onInput={(e) => {
                        const target = e.target as HTMLInputElement
                        inputTargetVal = Number(target.value)
                    }} type='digit'></Input> : null
                }

            </AtModalContent>
            <AtModalAction>
                <Button onClick={() => setEditVisible(false)}>取消</Button>
                <Button onClick={() => updateTarget()}>确定</Button>
            </AtModalAction>
        </AtModal>
    </View>
})

export default MonthInfo